<template>
  <div id="app">
    <div class="column_container">
      <div class="row_container">
        <div class="svg_container">
          <h1>Visualization</h1>
          <div>
            <el-select v-model="nationName" placeholder="select nation">
              <el-option
                class="big_text"
                v-for="nation in nations"
                :key="nation.indicator"
                :label="nation.indicator"
                :value="nation.indicator"
              >
              </el-option>
            </el-select>
            <el-select
              style="margin-left: 20px"
              v-model="featureName"
              placeholder="select feature"
            >
              <el-option
                v-for="feature in columnNames"
                :key="feature"
                :label="feature"
                :value="feature"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="data_container">
          <h1>Data Console</h1>
          <el-tabs v-model="activeName">
            <el-tab-pane label="Interpolation" name="Interpolation">
            </el-tab-pane>
            <el-tab-pane label="Compare" name="Compare"></el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <div class="row_container">
        <div class="scroll_container" @scroll="handleScroll">
          <svg class="svg_element" id="my_svg"></svg>
        </div>
        <div class="scroll_container">
          <interpolation
            :nation="curNation"
            :layout="layout"
            v-if="activeName == 'Interpolation'"
          ></interpolation>
          <compare :nation="curNation" v-if="activeName == 'Compare'"></compare>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import colorSet from './assets/js/color'
import frame from './assets/js/frame'
// import {selected} from './assets/js/frame.js'
import d3 from 'd3'
import Interpolation from '@/components/Interpolation'
import Compare from '@/components/Compare.vue'
export default {
  name: 'App',
  components: {
    Interpolation,
    Compare
    // HelloWorld
  },
  data () {
    return {
      nationName: '',
      featureName: 'population',
      layout: {
        'width': 1960,
        "height": 1960,
        'margin': { top: 20, right: 20, bottom: 20, left: 40 },
        'xMin': 0,
        'xMax': 1,
        'yMin': 0,
        'yMax': 1
      },
      selectedCircleId: undefined,
      nations: [],
      curNation: {},
      minMaxData: [],
      activeName: "Interpolation",
      columnNames: ['population', 'surface area (Km2)', 'GINI index', 'happy planet index',
        'human development index', 'world happiness report score', 'sustainable economic development assessment (SEDA)',
        'GDP (billions PPP)', 'GDP per capita (PPP)', 'GDP growth(annual %)', 'health expenditure % of GDP',
        'health expenditure per person', 'education expenditure% of GDP', 'education expenditure per person',
        'school life expectancy (YEARS)', 'unemployment (%)', 'government spending score',
        'government expenditure (% of GDP)', 'political rights score', 'civil liberties score',
        'political stability & absence of violence', 'government effectiveness', 'regulatory quality',
        'rule of law', 'control of corruption', 'judicial effectiveness score', 'government integrity score',
        'property rights score', 'tax burden score', 'overall economic freedom score', 'financial freedom score', 'women MPs (% of all MPs)']

    }
  },
  mounted () {
    this.draw()
    frame.frame()
    // window.addEventListener('scroll',this.handleScroll)
  },
  watch: {
    featureName () {
      this.updateDraw()
    },
    nationName (newValue) {
      console.log('select', newValue)
      for (let i in this.nations) {
        if (this.nations[i].indicator === newValue) {
          this.clickF(this.nations[i], i)
        }
      }
    }
  },
  methods: {
    handleScroll (e) {
      console.log(e.srcElement.scrollTop)
      this.$store.commit('setOffset', { t: e.srcElement.scrollTop, l: e.srcElement.scrollLeft })
    },
    mouseoverF (data) {
      // console.log(data)
      this.curNation = data
    },
    updateDraw () {
      let rMax = this.minMaxData[this.featureName + "Max"]
      let rMin = this.minMaxData[this.featureName + "Min"]
      let xMin = this.minMaxData['xMin']
      let xMax = this.minMaxData['xMax']
      let yMin = this.minMaxData['yMin']
      let yMax = this.minMaxData['yMax']
      console.log("update")
      let width = this.layout.width - this.layout.margin.right - this.layout.margin.left
      let height = this.layout.height - this.layout.margin.top - this.layout.margin.bottom

      let xRate = width / (xMax - xMin)
      let yRate = height / (yMax - yMin)
      d3.selectAll(".dot").transition()
        .attr('r', d => calcR(d[this.featureName]))
        .duration(200)

      d3.selectAll('text')
        .transition()
        .duration(200)
        .attr('x', d => calcX(d.x))
        .attr('y', d => calcY(d.y) - calcR(d[this.featureName]) - 3)
        .text(d => calcR(d[this.featureName]) < 5.1 ? '' : d.indicator)
      function calcR (r) {
        return (r - rMin) / (rMax - rMin) * 10 + 5
      }
      function calcX (x) {
        return (x - xMin) * xRate
      }
      function calcY (y) {
        return (y - yMin) * yRate
      }
    },
    clickF (data, id) {
      this.curNation = data
      if (this.selectedCircleId) {
        d3.select('#svg').select('#c' + this.selectedCircleId)
          .transition().duration(300).attr('fill', colorSet.defaultCircleColor)
      }
      d3.select('#svg').select('#c' + id).transition().duration(300).attr('fill', colorSet.selectedCircleColor)
      this.selectedCircleId = id
    },
    draw () {
      let width = this.layout.width - this.layout.margin.right - this.layout.margin.left
      let height = this.layout.height - this.layout.margin.top - this.layout.margin.bottom
      const SVGCx = d3.select('svg').attr("id", "my_svg").attr('width', this.layout.width).attr("height", this.layout.height)

      var svg = SVGCx.append("g").attr("id", "svg")
        .attr("transform", "translate(" + this.layout.margin.left + "," + this.layout.margin.top + ")")
      let that = this
      d3.csv('formatData.csv', function (nations) {
        that.nations = nations
        console.log(nations)
        let xMax, xMin, yMax, yMin
        let xarr = nations.map(d => parseFloat(d.x))
        let yarr = nations.map(d => parseFloat(d.y))
        for (let column of that.columnNames) {
          let arr = nations.map(d => parseFloat(d[column]))
          that.minMaxData[column + "Max"] = Math.max(...arr)
          that.minMaxData[column + "Min"] = Math.min(...arr)
        }
        xMax = Math.max(...xarr)
        xMin = Math.min(...xarr)
        yMax = Math.max(...yarr)
        yMin = Math.min(...yarr)
        that.minMaxData['xMin'] = xMin
        that.minMaxData['xMax'] = xMax
        that.minMaxData['yMin'] = yMin
        that.minMaxData['yMax'] = yMax
        that.layout.xMin = xMin
        that.layout.xMax = xMax
        that.layout.yMin = yMin
        that.layout.yMax = yMax
        let xRate = width / (xMax - xMin)
        let yRate = height / (yMax - yMin)
        let rMax = that.minMaxData[that.featureName + "Max"]
        let rMin = that.minMaxData[that.featureName + "Min"]
        console.log("minmaxdata", that.minMaxData)
        svg.selectAll(".dot").data(nations)
          .enter()
          .append('circle')
          // .on("mouseover", that.mouseoverF)
          .on('click', (d, id) => that.clickF(d, id))
          .attr('class', 'dot')
          .attr('id', (d, i) => "c" + i)
          .attr('cx', d => calcX(d.x))
          .attr('cy', d => calcY(d.y))
          .attr('r', d => calcR(d[that.featureName]))
          .attr('fill', colorSet.defaultCircleColor
          )
        svg.selectAll('text').data(nations)
          .enter()
          .append('text')
          .style('font-size','13px')
          .attr("text-anchor", "middle")
          .attr('x', d => calcX(d.x))
          .attr('y', d => calcY(d.y) - calcR(d[that.featureName]) - 3)
          .text(d => calcR(d[that.featureName]) < 5.1 ? '' : d.indicator)
        function calcX (x) {
          return (x - xMin) * xRate
        }
        function calcY (y) {
          return (y - yMin) * yRate
        }
        function calcR (r) {
          return (r - rMin) / (rMax - rMin) * 10 + 5
        }
      })


    }

  }

}
</script>

<style>
line {
  stroke: rgb(0, 255, 0);
  stroke-width: 2;
}
.row_container {
  display: flex;
  flex-direction: row;
}
.column_container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.dot:hover {
  fill: yellow;
}
.svg_container {
  margin: 10px;
  width: 50%;
  height: 100%;
}
.data_container {
  margin: 10px;

  width: 50%;
}
.scroll_container {
  width: 50%;
  margin-top: 15px;
  height: 650px;
  overflow: auto;
  margin: 10px;
  flex-basis: 1;
}
#app {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
}
</style>
